/**
 * ReceiverHelper
 * Copyright(C) 2018 liumurong
 */

import { Receiver } from "./receiver";
import { SliceOptions } from "./models";
import * as path from "path";
import { MongoReceiver } from "./mongoreceiver";
import { LocalReceiver } from "./localreceiver";
import { scheduleJob } from 'node-schedule';
/**
 * 
 */
export class ReceiverHelper {

    private static _instance: ReceiverHelper;
    private _receiver: Receiver;
    private _fieldname: string;

    /**
     * ReceiverHelper
     */
    private constructor() { }

    /**
     * 
     */
    static get instance() {
        if (!this._instance) {
            this._instance = new ReceiverHelper()
        }
        return this._instance;
    }

    /**
     * Receiver
     */
    get receiver() {
        return this._receiver;
    }
    /**
     * HashName
     */
    get hashFieldName() {
        return this._fieldname;
    }

    /**
     * 配置
     * 此方法至少需要调用一次
     * @param opts 选项
     */
    setOptions(opts: SliceOptions = { localstoredirectory: path.join(__dirname, "../uploads") }) {
        this._fieldname = opts.hashfieldname || "filehash";
        if (opts.mongoconnstring) {
            this._receiver = new MongoReceiver(opts.mongoconnstring);
            return;
        }
        this._receiver = new LocalReceiver(opts.localstoredirectory);
    }
    /**
     * 启动计划任务
     * 删除垃圾文件
     */
    startScheduleTask() {
        if (!this._receiver) {
            return;
        }
        // 每天凌晨3点执行任务
        scheduleJob("* * 3 * * *", () => {
            this._receiver.removeUnIntegralResourceFiles();
        });
    }


}



